<?php
defined('SYSPATH') or die('No direct script access.');

/**
 * Article controller (Admin)
 *
 * @author an.cao <a@clgt.vn>
 * @since May 2011
 */
class Controller_Admin_Article extends Controller_Admin_Layout
{

    /**
     * Show all articles in database
     * 
     * @access public
     */
    public function action_manage($page = 1)
    {
        $pager = new Doctrine_Pager(
                Doctrine_Query::create()
                    ->from( 'Article a' )
                    ->orderby( 'a.id DESC' ),
                $page
                );
        
        $pager->getExecuted();
        $articles = $pager->execute();

        $page_ranger = new Doctrine_Pager_Range_Sliding(array('chunk' => 5),
                    $pager);

        $pagination = new Doctrine_Pager_Layout($pager, $page_ranger, Url::site('admin/article/manage/{%page}'));
        $pagination->setTemplate('<a href="{%url}" class="number" title="Trang {%page}">{%page}</a>');
        $pagination->setSelectedTemplate('<a href="{%url}" class="number current" title="Trang {%page}">{%page}</a>');

        $this->template->main = View::factory('admin/article_manage', array(
            'articles'   => $articles,
            'pagination' => $pagination,
            'category'   => Libs_Category::getInstance()->render('category_id'),
            'pending_articles' => Doctrine_Query::create()
                                            ->from('Article a')
                                            ->where('a.status = ?', Article::STATUS_PENDING)->orderBy('a.id DESC')->execute()
        ));
    }

    /**
     * Search artiles with the given keywords
     *
     * @access public
     * @param <int> $page
     */
    public function action_search($page = 1)
    {
        $post = Arr::extract($_POST, array('keyword'));
        if($post['keyword'] == NULL)
        {
            $this->request->redirect(Url::site('admin/article/manage'));
        }
        
        $pager = new Doctrine_Pager(
                Doctrine_Query::create()
                    ->from( 'Article a' )
                    ->where('a.title LIKE ?', '%'.$post['keyword'].'%')
                    ->orderby( 'a.id DESC' ),
                $page
                );

        $pager->getExecuted();
        $articles = $pager->execute();

        $page_ranger = new Doctrine_Pager_Range_Sliding(array('chunk' => 5),
                    $pager);

        $pagination = new Doctrine_Pager_Layout($pager, $page_ranger, Url::site('admin/article/manage/{%page}'));
        $pagination->setTemplate('<a href="{%url}" class="number" title="Trang {%page}">{%page}</a>');
        $pagination->setSelectedTemplate('<a href="{%url}" class="number current" title="Trang {%page}">{%page}</a>');

        $this->template->main = View::factory('admin/article_manage', array(
            'articles'   => $articles,
            'pagination' => $pagination
        ));
    }

    /**
     * Create a new article
     *
     * @access public
     * @return <type>
     */
    public function action_create()
    {
        $data = array();
        // Data is submitted
        if($this->request->method() === 'POST')
        {
            $post = Validation::factory($_POST)
                    ->rule(TRUE, 'trim')
                    ->rule('title', 'not_empty')
                    ->rule('title', 'max_length', array(':value', 255));

            // Data is valid
            if($post->check() == TRUE)
            {
                $post = Arr::extract($_POST, array('title', 'summary', 'content', 'category_id','status'));

                try
                {
                    $article = new Article();
                    $article->title       = $post['title'];
                    $article->category_id = $post['category_id'];
                    $article->summary     = $post['summary'];
                    $article->content     = $post['content'];
                    $article->status      = $post['status'];

                    $user_info = Api::load('user')->get_user_info();
            
                    /**
                     * if user not login with admin role, and then set land status to pending
                     */
                    if(!Api::load('user')->has_role($user_info['id'],'admin'))
                    {
                        $article->status = Article::STATUS_PENDING;
                    }
                    
                    $article->save();

                    $data['message'] = array(
                        'type'    => 'success',
                        'content' => 'Đăng bài viết thành công'
                    );
                }
                catch (Exception $ex)
                {
                    $data['message'] = array(
                        'type'    => 'success',
                        'content' => $ex->getMessage()
                    );
                }
            }
            else
            {
                $data['message'] = array(
                    'type'    => 'error',
                    'content' => 'Dữ liệu nhập vào không hợp lệ. Vui lòng thử lại'
                );
            }
        }

        $this->add_scripts(Url::vendors().'tiny_mce/jquery.tinymce.js');
        $this->add_scripts(Url::admin_assets().'js/tinymce.js');

        $data['category'] = Libs_Category::getInstance()->render('category_id');

        $this->template->main = View::factory('admin/article_create', $data);
    }

    /**
     * Edit an article
     *
     * @access public
     * @param <int> $id
     */
    public function action_edit($id)
    {
        if((int) $id <= 0)
        {
            $this->request->redirect(Url::site('admin/article/manage'));
        }

        $data = array();

        $article = ArticleTable::getInstance()->find($id);
        if($article == NULL)
        {
            $this->request->redirect(Url::site('admin/article/manage'));
        }
        
        // If there are submitted data
        if($this->request->method() === 'POST')
        {
            $article->setArray(Arr::extract($_POST,
                    array('title', 'summary', 'content', 'category_id','status')));
            
            $user_info = Api::load('user')->get_user_info();
            
            /**
             * if user not login with admin role, and then set land status to pending
             */
            if(!Api::load('user')->has_role($user_info['id'],'admin'))
            {
                $article->status = Article::STATUS_PENDING;
            }
            
            $article->save();
        }

        $this->add_scripts(Url::vendors().'tiny_mce/jquery.tinymce.js');
        $this->add_scripts(Url::admin_assets().'js/tinymce.js');

        $data['article'] = $article;
        $data['category']   = Libs_Category::getInstance()->render('category_id');

        $this->template->main = View::factory('admin/article_edit', $data);
    }

    /**
     * Delete selected articles
     *
     * @access public
     */
    public function action_delete($id = NULL)
    {
        // If not direct access
        if(! ($this->request->method() === 'GET' && $id === NULL))
        {
            try
            {
                $query = Doctrine_Query::create()
                        ->delete('Article a');

                // Bulk delete
                if(isset($_POST['submit']) === TRUE)
                {
                    $post = Arr::extract($_POST, array('article_id'));
                    if(count($post['article_id']) > 0)
                    {
                        $query->whereIn('a.id', $post['article_id']);
                    }
                }

                // If a single artilce
                if((int) $id > 0)
                {
                    $query->where('a.id = ?', $id);
                }

                // Execute query
                $query->execute();
            }
            catch(Exception $ex)
            {
                // TODO: Handle errors
            }
        }

        $this->request->redirect(Url::site('admin/article/manage'));
    }


    /**
     * Quán lý bài viết theo danh mục
     *
     * @access public
     * @param <int> $category_id
     * @param <int> $page
     */
    public function action_category($category_id, $page = 1)
    {
        $category_id = (int) $category_id;
        if($category_id <= 0)
        {
            throw new Exception('Danh mục không hợp lệ');
        }

        $pager = new Doctrine_Pager(
                Doctrine_Query::create()
                    ->from( 'Article a' )
                    ->where('a.category_id = ?', $category_id)
                    ->orderby( 'a.id DESC' ),
                $page);

        $pager->getExecuted();
        $articles = $pager->execute();

        $page_ranger = new Doctrine_Pager_Range_Sliding(array('chunk' => 5),
                    $pager);

        $pagination = new Doctrine_Pager_Layout($pager, $page_ranger, Url::site('admin/article/category/'.$category_id.'/page-{%page}'));
        $pagination->setTemplate('<a href="{%url}" class="number" title="Trang {%page}">{%page}</a>');
        $pagination->setSelectedTemplate('<a href="{%url}" class="number current" title="Trang {%page}">{%page}</a>');

        $this->template->main = View::factory('admin/article_manage', array(
            'articles'   => $articles,
            'pagination' => $pagination,
            'category'   => Libs_Category::getInstance()->render('category_id')
        ));
    }
}